<!-- 左树右表格demo -->
<template>
  <div class="common-equipment-model">
    <div>
      <!--      左边的树   -->
      <!--      :props="{ label: 'name' }" 要显示在树上的中文-->
      <ele-tree-composite-table
        v-loading="loading"
        leftWidth="24%"
        :formConfig="searchConfig"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getDataList"
        ref="treeCompositeTable"
        @node-click="handleNodeClick"
        :getParamsFromNode="getParamsFromNode"
        :treeApi="getTreeByFactory"
        :props="{ label: 'label' }"
        uniqueId="mesMaterialStationModelTable"
      >
        <template v-slot:default="{ data }">
          <div class="flex label-pack">
            <span class="padd-r-5">
              <img v-if="data.data.children" src="@/assets/images/xia.png" />
              <img v-else src="@/assets/images/ping.png" />
            </span>
            <svgIcon
              :color="data.node.isCurrent ? '#3d82ea' : '#b6c0c9'"
              :type="
                (
                  iconType.find((ite) => data.data.level == ite.value) || {
                    type: -1,
                  }
                ).type
              "
              :modelingType="data.data.modelingType"
            />
            <span class="tree-label">{{ data.node.label }}</span>
          </div>
        </template>
      </ele-tree-composite-table>
    </div>
    <!--  修改弹窗  -->
    <ele-form-drawer
      size="40%"
      :isLoading="formConfirmLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
      <!-- <template v-slot:farmCode>
            <el-input v-model="formDataDialog.farmCode" readonly>
                <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="mesMaterialStationModelingDialogVisible = true"
                ></el-button>
            </el-input>
        </template> -->
      <template v-slot:stationCode>
        <el-input
          v-model="formDataDialog.stationCode"
          readonly
          :placeholder="$t('mesMaterialStationModel.placeSelectStation')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="mesMaterialStationInventoryDialogVisible = true"
          ></el-button>
        </el-input>
      </template>
      <template v-slot:equipmentCode>
        <!-- 插槽内容有el-form-item组件包裹 -->
        <el-input
          v-model="formDataDialog.equipmentCode"
          readonly
          :placeholder="$t('mesMaterialStationModel.pleaseSelectEquipment')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="commonBaseEquipmentDocumentDialogVisible = true"
          ></el-button>
        </el-input>
      </template>
      <template v-slot:prodCode>
        <el-input
          v-model="formDataDialog.prodCode"
          readonly
          :placeholder="$t('mesMaterialStationModel.pleaseSelectProduct')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="baseGoodsDialogVisible = true"
          ></el-button>
        </el-input>
      </template>
      <template v-slot:materialCode>
        <el-input
          v-model="formDataDialog.materialCode"
          readonly
          :placeholder="$t('mesMaterialStationModel.pleaseSelectMaterial')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="bomDialogVisible = true"
          ></el-button>
        </el-input>
      </template>
    </ele-form-drawer>
    <!-- <ele-dialog-table
            :title="$t('mesMaterialStationModel.selectEquipment')"
            width="800px"
            :visible.sync="mesMaterialStationModelingDialogVisible"
            :formConfig="mesMaterialStationModelingSearchDialog"
            :column="mesMaterialStationModelingDialogColumn"
            @getSelectData="getSelectMesMaterialStationModeling"
            :getList="getMesMaterialStationModelingList"
            :hasFooter="hasMesMaterialStationModelingFooter"
            :pagination="false"
            row-key="id"
            :transFormdata="transFormdata"
            :tree-props="{ children: 'children' }"
        >
        </ele-dialog-table> -->
    <ele-dialog-table
      :title="$t('mesMaterialStationModel.selectStation')"
      width="900px"
      :visible.sync="mesMaterialStationInventoryDialogVisible"
      :formConfig="mesMaterialStationInventorySearchDialog"
      :column="mesMaterialStationInventoryDialogColumn"
      @getSelectData="getSelectMesMaterialStationInventory"
      :otherParam="{ status: '1' }"
      :getList="getMesMaterialStationInventoryList"
      :hasFooter="hasMesMaterialStationInventoryFooter"
    ></ele-dialog-table>
    <ele-dialog-table
      :title="$t('mesMaterialStationModel.selectEquipment')"
      width="800px"
      :visible.sync="commonBaseEquipmentDocumentDialogVisible"
      :formConfig="commonBaseEquipmentDocumentSearchDialog"
      :column="commonBaseEquipmentDocumentDialogColumn"
      :otherParam="{
        modelingCode: !!formDataDialog.workCellCode
          ? formDataDialog.workCellCode
          : !!formDataDialog.lineCode
          ? formDataDialog.lineCode
          : formDataDialog.farmCode,
      }"
      @getSelectData="getSelectCommonBaseEquipmentDocument"
      :getList="commonBaseEquipment"
      :hasFooter="hasCommonBaseEquipmentDocumentFooter"
    ></ele-dialog-table>
    <ele-dialog-table
      :title="$t('mesProdBom.addProduct')"
      width="800px"
      :visible.sync="baseGoodsDialogVisible"
      :formConfig="baseGoodsSearchDialog"
      :column="baseGoodsDialogColumn"
      @getSelectData="getSelectBaseGoods"
      :getList="pageBcpAndCp"
      :hasFooter="hasBaseGoodsFooter"
    ></ele-dialog-table>
    <ele-dialog-table
      :title="$t('mesProdBom.addMaterial')"
      width="800px"
      ref="tabledialog"
      :otherParam="{ excludeGoodsCode: formDataDialog.productCode }"
      :visible.sync="bomDialogVisible"
      :formConfig="baseGoodsSearchDialog"
      :column="baseGoodsDialogColumn"
      @getSelectData="getSelectBaseGoodsBoom"
      :getList="pageExclude"
      :hasFooter="true"
    ></ele-dialog-table>
    <!-- 导入弹框 -->
    <ele-form-drawer
      size="30%"
      :isLoading="isLoadingImport"
      v-model="importData"
      v-bind="importFormDescDialog"
      :request-fn="handleSubmitImport"
      :visible.sync="importVisible"
      :destroyOnClose="true"
      :title="$i18n.t('common.import')"
    >
      <template v-slot:file="{ desc, data, field, formData }">
        <!-- 插槽内容有el-form-item组件包裹 -->
        <uploadNoAuto @onchange="upLoadHandleChange" ref="uploadNoAuto" />
      </template>
    </ele-form-drawer>
  </div>
</template>
<script>
import {
  operateList,
  searchConfig,
  //formDescDialog,
  rowConfig,
  formDescDialogMixin,
  importFormDescDialog,
} from "./config";
import { pageExclude } from "@/api/process/mesProcessMaterial";
import svgIcon from "./components/svgIcon.vue";
import { getUnitDictList } from "@/api/common";
import {
  getDataList, // 表格查询
  getTreeByFactory, // 树查询
  getInfo, // 获取详情
  submitDelete, // 删除
  submitEdit, // 修改
  submitCreate, // 新增
  getStatusList,
  getTypeCodeList,
  importData,
} from "@/api/materialStation/mesMaterialStationModel";
import { commonBaseEquipmentDocumentDialog } from "./equipmentMixin";
import { mesMaterialStationInventoryDialog } from "./stationMixin";
// import { mesMaterialStationModelingDialog } from "./modelingMixin"
import { baseGoodsDialog } from "../../materials/mesProdBom/mixin";
import uploadNoAuto from "@/components/upload-no-auto";
export default {
  name: "mesMaterialStationModel",
  mixins: [
    commonBaseEquipmentDocumentDialog,
    baseGoodsDialog,
    mesMaterialStationInventoryDialog,
    // mesMaterialStationModelingDialog,
    formDescDialogMixin,
  ],
  components: { svgIcon, uploadNoAuto },
  data() {
    return {
      addData: {},
      iconType: [
        {
          value: 2,
          name: $i18n.t("mesMaterialStationModel.industry"),
          type: 5,
        },
        {
          value: 6,
          name: $i18n.t("mesMaterialStationModel.workCell"),
          type: 4,
        },
        { value: 5, name: $i18n.t("mesMaterialStationModel.line"), type: 3 },
        { value: 4, name: $i18n.t("mesMaterialStationModel.farm"), type: 2 },
        { value: 3, name: $i18n.t("mesMaterialStationModel.factory"), type: 1 },
        {
          value: 99,
          name: $i18n.t("mesMaterialStationModel.enterprise"),
          type: 0,
        },
        { value: -1, name: $i18n.t("baseFactoryModeling."), type: -1 },
      ],
      // 查询表格时获取子节点的字段，value 取节点的哪一个字段值，key请求时传的key
      // value是点击左边树时要获取对象的哪个属性，eg object.id就写id;key是做表格查询时传入的搜索条件的name
      getParamsFromNode: {
        column: [
          { value: "modelingCode", key: "modelingCode" },
          { value: "level", key: "modelingLevel" },
        ], //设备编码
      },
      pageExclude,
      loading: false, // 页面loading
      formConfirmLoading: false, // 弹框确定的loading
      bomDialogVisible: false,
      searchConfig,
      operateList,
      title: null, // 修改|新增弹框标题
      submitFarmList: [],
      submitLineList: [],
      submitCellList: [],
      formDataDialog: {}, // 修改|新增弹框表单数据
      //formDescDialog, // 修改|新增弹框表单配置
      visible: false, // 修改|新增弹框显示隐藏
      getDataList, // 表格查询
      getTreeByFactory, // 树查询
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
          fixed: "left",
        },
        {
          prop: "stationCode",
          label: $i18n.t("mesMaterialStationModel.stationCode"),
          minWidth: 160,
          showOverflowTooltip: true,
        },
        {
          prop: "stationName",
          label: $i18n.t("mesMaterialStationModel.stationName"),
          minWidth: 250,
          showOverflowTooltip: true,
        },
        {
          prop: "workshopCode",
          label: $i18n.t("mesMaterialStationModel.workshopCode"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "workshopName",
          label: $i18n.t("mesMaterialStationModel.workshopName"),
          minWidth: 200,
          showOverflowTooltip: true,
        },
        {
          prop: "lineCode",
          label: $i18n.t("mesMaterialStationModel.lineCode"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "lineName",
          label: $i18n.t("mesMaterialStationModel.lineName"),
          minWidth: 200,
          showOverflowTooltip: true,
        },
        {
          prop: "workCellCode",
          label: $i18n.t("mesMaterialStationModel.workCellCode"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "workCellName",
          label: $i18n.t("mesMaterialStationModel.workCellName"),
          minWidth: 200,
          showOverflowTooltip: true,
        },
        {
          prop: "equipmentCode",
          label: $i18n.t("mesMaterialStationModel.equipmentCode"),
          minWidth: 150,
          showOverflowTooltip: true,
        },
        {
          prop: "equipmentName",
          label: $i18n.t("mesMaterialStationModel.equipmentName"),
          minWidth: 250,
          showOverflowTooltip: true,
        },
        {
          prop: "typeCode",
          label: $i18n.t("mesMaterialStationModel.typeCode"),
          minWidth: 100,
          showOverflowTooltip: true,
          optionProp: {
            value: "typeCode",
            label: "typeName",
          },
          //远程获取
          option: async (data) => {
            const list = await getTypeCodeList();
            return list.data.result;
          },
        },
        {
          prop: "prodCode",
          label: $i18n.t("mesMaterialStationModel.prodCode"),
          minWidth: 150,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesMaterialStationModel.prodName"),
          minWidth: 250,
          showOverflowTooltip: true,
        },
        {
          prop: "materialCode",
          label: $i18n.t("mesMaterialStationModel.materialCode"),
          minWidth: 150,
          showOverflowTooltip: true,
        },
        {
          prop: "materialName",
          label: $i18n.t("mesMaterialStationModel.materialName"),
          minWidth: 250,
          showOverflowTooltip: true,
        },
        {
          prop: "volume",
          label: $i18n.t("mesMaterialStationModel.volume"),
          minWidth: 100,
          showOverflowTooltip: true,
        },
        {
          prop: "unitCode",
          label: $i18n.t("mesMaterialStationModel.unit"),
          minWidth: 100,
          showOverflowTooltip: true,
          optionProp: {
            value: "value",
            label: "description",
          },
          //远程获取
          option: async (data) => {
            const list = await getUnitDictList();
            return list.data.result;
          },
        },
        {
          prop: "safetyStock",
          label: $i18n.t("mesMaterialStationModel.safetyStock"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "unitConsumption",
          label: $i18n.t("mesMaterialStationModel.unitConsumption"),
          minWidth: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "status",
          label: $i18n.t("mesMaterialStationModel.status"),
          minWidth: 100,
          showOverflowTooltip: true,
          optionProp: {
            value: "value",
            label: "description",
          },
          //远程获取
          option: async (data) => {
            const list = await getStatusList();
            return list.data.result;
          },
        },
        {
          prop: "createByName",
          label: $i18n.t("common.createByName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "updateByName",
          label: $i18n.t("common.updateByName"),
          minWidth: 130,
          showOverflowTooltip: true,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: 160,
          fixed: "right",
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              ></ele-row-operation>
            );
          },
        },
      ],
      isLoadingImport: false, // 导入数据loading
      importData: {}, //导入数据
      importVisible: false,
      importFormDescDialog, // 导入字段配置
    };
  },
  computed: {},
  methods: {
    handleNodeClick(data, node, item) {
      let list = getParentsById(item.tree.data, data.id);
  
      this.addData = {};
      list.map((ite) => {
        let { modelingCode } = ite;
        if (ite.level == 4) {
          this.addData.workshopCode = modelingCode;
          this.addData.farmCode2 = modelingCode;
        }
        if (ite.level == 5) {
          this.addData.lineCode = modelingCode;
          this.addData.lineCode2 = modelingCode;
        }
        if (ite.level == 6) {
          this.addData.workCellCode = modelingCode;
          this.addData.workCellCode3 = modelingCode;
        }
      });
      console.log(234,this.addData,list)
      function getParentsById(list, id) {
        for (let i in list) {
          if (list[i].id === id) {
            //查询到就返回该数组对象
            return [list[i]];
          }
          if (list[i].children) {
            let node = getParentsById(list[i].children, id);
            if (node !== undefined) {
              //查询到把父节点连起来
              return node.concat(list[i]);
            }
          }
        }
      }

      return;
      let a = getCode(item.tree.data);
      console.log(22222, a, data, item.tree.data);
      function getCode(list) {
        let arr = [];
        for (let i = 0; i < list.length; i++) {
          const items = list[i];
          if (items.id == data.id) {
            arr.push(items);
            return arr;
          }
          if (items.children) {
            arr.push(items);
            getCode(items.children);
          } else {
            arr = [];
          }
        }
      }
    },
    // 顶部按钮操作
    handleOperateEvent({ name, handleName, rows }) {
      this.title = name;
      const fnc = {
        // 新增操作
        add: () => {
          this.formDataDialog = { status: "1",...this.addData };
          this.formDescDialog.disabled = false;
          this.formDescDialog.isShowSubmitBtn = true;
          this.visible = true;
        },
        // 删除操作
        delete: () => {
          this.$confirm(
            $i18n.t("common.deleteBatch", {
              name: $i18n.t("mesMaterialStationModel.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = rows.map((val) => val.id);
            this.doDelete({ ids });
          });
        },
        import: () => {
          this.importDialogData = {};
          this.importVisible = true;
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          this.getInfo(row.id, true);
        },
        info: () => {
          this.getInfo(row.id, false);
        },
        delete: () => {
          this.$confirm(
            $i18n.t("common.deleteSingle", {
              name: $i18n.t("mesMaterialStationModel.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            let ids = [row.id];
            this.doDelete({ ids });
          });
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    // 删除
    doDelete(data) {
      submitDelete(data).then((res) => {
        const msg = res.data.message;
        this.$message.success(msg || $i18n.t("common.deleteSuccess"));
        this.refresh(true);
      });
    },
    // 获取详情
    getInfo(id, isEdit) {
      this.loading = true;
      if (isEdit) {
        this.formDescDialog.disabled = false;
        this.formDataDialog.isShowSubmitBtn = true;
      } else {
        console.log("仅查看");
        this.formDescDialog.disabled = true;
        this.formDataDialog.isShowSubmitBtn = false;
        console.log(this.formDataDialog);
      }
      getInfo(id)
        .then((res) => {
          this.formDataDialog = res.data.result;
          this.formDataDialog.farmCode2 = this.formDataDialog.workshopCode;
          this.formDataDialog.lineCode2 = this.formDataDialog.lineCode;
          this.formDataDialog.workCellCode3 = this.formDataDialog.workCellCode;


          this.visible = true;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 弹框提交事件
    handleSubmit(data) {
      if (this.formConfirmLoading) return; // 判断状态
      const params = this.formDataDialog.id
        ? { title: $i18n.t("common.editSuccess"), api: submitEdit, data }
        : { title: $i18n.t("common.addSuccess"), api: submitCreate, data };
      this.submit(params);
    },
    // 新增和修改提交事件
    submit({ title, api, data }) {
      this.formConfirmLoading = true;
      // checkbox处理
      api(data)
        .then((res) => {
          const msg = res.data.message;
          this.$message.success(msg || title);
          this.visible = false;
          this.refresh(true);
        })
        .finally(() => {
          this.formConfirmLoading = false;
        });
    },
    // 刷新表格数据 isReset 是否重新刷新(包括左边树结构的刷新)
    refresh(isReset = false) {
      this.$refs.treeCompositeTable.refresh(isReset);
    },
    getSelectBaseGoods(data) {
      // 第一个入参为当前表单绑定的对象，第二个入参为要修改的字段名，第三个入参为选中数据中相应信息
      this.$set(this.formDataDialog, "prodCode", data[0].goodsCode);
      this.$set(this.formDataDialog, "prodName", data[0].goodsName);
    },
    getSelectBaseGoodsBoom(data) {
      // 第一个入参为当前表单绑定的对象，第二个入参为要修改的字段名，第三个入参为选中数据中相应信息
      this.$set(this.formDataDialog, "materialCode", data[0].goodsCode);
      this.$set(this.formDataDialog, "materialName", data[0].goodsName);
    },
    getSelectCommonBaseEquipmentDocument(data) {
      // 第一个入参为当前表单绑定的对象，第二个入参为要修改的字段名，第三个入参为选中数据中相应信息
      this.$set(this.formDataDialog, "equipmentCode", data[0].equipmentCode);
      this.$set(this.formDataDialog, "equipmentName", data[0].equipmentName);
    },
    //表格数据转化，一般不需要转化
    transFormdata(data) {
      return Promise.resolve({ records: data.data.result, total: 0 });
    },
    upLoadHandleChange(file) {
      this.$set(this.importData, "file", file);
    },
    handleSubmitImport() {
      if (!this.importData.file) {
        this.$message.error($i18n.t("common.uploadMsg"));
        return;
      }
      const formData = new FormData();
      formData.append("file", this.importData.file.get("file"));
      this.isLoadingImport = true;
      importData(formData)
        .then((res) => {
          this.$message.success($i18n.t("common.importSuccess"));
          this.isLoadingImport = false;
          this.importVisible = false;
          this.refresh();
        })
        .catch((error) => {
          console.log("错误", error);
          this.$set(this.importData, "file", null);
        })
        .finally(() => {
          this.isLoadingImport = false;
          this.$refs.uploadNoAuto.clearFiles();
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.common-equipment-model {
  .flex {
    display: flex;
  }

  .label-pack {
    display: flex;
    align-items: center;
    span {
      display: flex;
      align-items: center;
    }

    .padd-r-5 {
      padding-right: 5px;
    }
    .tree-label {
      padding-left: 5px;
      font-size: 14px;
    }
  }
}
</style>
